package net.pulseproject.commons.util;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//FIXME delete, as its a duplicate of josceleton version
public final class IoUtil {

	private static final Log LOG = LogFactory.getLog(IoUtil.class);

	private IoUtil() {
		// util classes should not be instantiated
	}
	
	public static Properties loadPropertiesFromClassPath(final ClassLoader loader,
			final String fileName) throws IOException {
		LOG.info("loadPropertiesFromClassPath(loader, fileName=[" + fileName + "])");
		if(loader == null) { throw new IllegalArgumentException("loader == null"); }
		if(fileName == null) { throw new IllegalArgumentException("fileName == null"); }
		if(fileName.isEmpty()) { throw new IllegalArgumentException("fileName is empty"); }
		
		final Properties properties = new Properties();
		InputStream inputStream = null;
		try {
			inputStream = loader.getResourceAsStream(fileName);
			if(inputStream == null) {
				throw new RuntimeException("Could not get resource [" + fileName + "] as stream!");
			}
			properties.load(inputStream);
		} finally {
			IoUtil.close(inputStream);
		}

		return properties;
	}

	public static boolean close(final Closeable closeable) {
		if (closeable == null) {
			return false;
		}
		
		try {
			closeable.close();
			return true;
		} catch (final IOException e) {
			LOG.warn("Could not close closeable [" + closeable.getClass().getSimpleName() + "]!", e);
			return false;
		}
	}
}
